package com.magic233.service;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.magic233.entity.Admins;
import com.magic233.entity.Users;
import com.magic233.entity.WeixinSession_keyAndOpenid;
import com.magic233.entity.Workers;
import com.magic233.mapper.AdminsMapper;
import com.magic233.mapper.UsersMapper;
import com.magic233.mapper.WorkersMapper;
import com.magic233.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: UsersServiceImpl
 * Description:
 * date: 2021/5/29 21:17
 * author: zouyuan
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AdminsMapper adminsMapper;

    @Autowired
    private WorkersMapper workersMapper;

    @Autowired
    private LogsService logsService;

    @Value("${weixin.appid}")
    private String appid;

    @Value("${weixin.secret}")
    private String secret;


    @Override
    public int addUser(Users user) {
        Users u = usersMapper.selectByPrimaryKey2(user.getId());
        if (u == null) {
            String password = user.getPassword();
            //密码加密
            user.setPassword(new BCryptPasswordEncoder().encode(password));
            int re = usersMapper.insert(user);
            if (re == 1) {
                String thing = "注册新用户：" + "{id:" + user.getId() + ",username:" + user.getUsername() + ",phone:" + user.getPhone() + "}";
                logsService.addLog(thing);
            }
            return re;
        }else {
            if(u.getDeleted() == 1){
                String password = user.getPassword();
                //密码加密
                user.setPassword(new BCryptPasswordEncoder().encode(password));
                int re = usersMapper.updateByPrimaryKeySelective(user);
                if (re == 1) {
                    String thing = "注册新用户：" + "{id:" + user.getId() + ",username:" + user.getUsername() + ",phone:" + user.getPhone() + "}";
                    logsService.addLog(thing);
                }
                return re;
            }else {
                return 0;
            }
        }
    }

    @Override
    public int verifyId(Long id) {
        Users user = usersMapper.selectByPrimaryKey(id);
        if (user == null) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public int verifyPhone(String phone) {
        Users user = usersMapper.selectUserByPhone(phone);
        if (user == null) {
            return 0;
        } else {
            return 1;
        }
    }

    @Override
    public Object login(String phone, String password) {
        Users u = new Users();
        u.setPhone(phone);
        u.setPassword(password);
        Users user = usersMapper.selectUserByPhone(u);
        Map<Object, Object> map = new HashMap<>();
        map.put("status", 2);
        map.put("token", null);
        map.put("user", null);
        if (user != null) {
            //验证密码
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            boolean isPass = passwordEncoder.matches(password, user.getPassword());
            if (isPass) {
                //获取权限
                List<String> role = new ArrayList<>();
                role.add("user");
                if ("Max".equals(user.getPower())) {
                    role.add("manager");
                }
                Admins admin = adminsMapper.selectByPrimaryKey(user.getId());
                if (admin != null) {
                    //普通管理员权限
                    role.add("admin");
                    if ("Max".equals(admin.getPower())) {
                        //超级管理员权限
                        role.add("superAdmin");
                    }
                }
                Workers worker = workersMapper.selectByPrimaryKey(user.getId());
                if (worker != null) {
                    //维修人员权限
                    role.add("worker");
                }
                user.setRole(role);

                String token = String.valueOf(UUID.randomUUID());
                Set<String> keys = redisTemplate.keys("*");
                for (String key : keys) {
                    System.out.println(key);
                    Users oldUser = null;
                    try {
                        oldUser = (Users) redisTemplate.opsForValue().get(key);
                        if (user.getPhone().equals(oldUser.getPhone())) {
                            System.out.println("账号已经登录，强制下线");
                            //将别处登录的账号key删除，即踢下线
                            redisTemplate.delete(key);
                            break;
                        }
                    } catch (Exception e) {
//                        e.printStackTrace();
                        System.out.println("转换失败" + key);
                    }
                }

                redisTemplate.opsForValue().set(token, user, 30, TimeUnit.MINUTES);

                System.out.println(user.getPhone() + ":登录成功");
                System.out.println("用户权限：" + role);
                map.put("status", 1);
                map.put("token", token);
                user.setPassword(null);
                map.put("user", user);
            }
        }
        return map;
    }

    @Override
    public Users bindOpenid(Users user, String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";
        String s = HttpUtil.doGet(url);
        System.out.println(s);

        WeixinSession_keyAndOpenid weixinSession_keyAndOpenid = JSON.parseObject(s, WeixinSession_keyAndOpenid.class);
        System.out.println(weixinSession_keyAndOpenid);
        if (weixinSession_keyAndOpenid.getOpenid() != null && !weixinSession_keyAndOpenid.getOpenid().equals("")) {
            user.setOpenid(weixinSession_keyAndOpenid.getOpenid());
            int i = usersMapper.updateOpenid(user);
            if (i == 1) {
                return user;
            }
        }
        user.setOpenid(null);
        return user;
    }

    @Override
    public int changePassword(Users user, String code, String password) {
        String phone = user.getPhone();
        String s = String.valueOf(redisTemplate.opsForValue().get(phone));
        if (s != null) {
            if (code.equals(s)) {
                //密码加密
                user.setPassword(new BCryptPasswordEncoder().encode(password));
                int re = usersMapper.updateByPrimaryKeySelective(user);
                if (re == 1) {
                    //去掉手机验证码
                    redisTemplate.delete(phone);
                    Set<String> keys = redisTemplate.keys("*");
                    for (String key : keys) {
                        System.out.println(key);
                        Users oldUser = null;
                        try {
                            oldUser = (Users) redisTemplate.opsForValue().get(key);
                            if (oldUser.getId().equals(user.getId())) {
                                System.out.println("去掉旧token");
                                redisTemplate.delete(key);
                                break;
                            }
                        } catch (Exception e) {
//                            e.printStackTrace();
                            System.out.println("转换失败" + key);
                        }

                    }
                    String thing = "用户：{" + user.getPhone() + "--" + user.getUsername() + "}修改了手机号";
                    logsService.addLog(thing);
                }
                return re;
            } else {
                return 2;
            }
        } else {
            return 0;
        }
    }

    @Override
    public int resetPassword(String phone, String code, String password) {
        String s = String.valueOf(redisTemplate.opsForValue().get(phone));
        if (s != null) {
            if (code.equals(s)) {
                //密码加密
                Users user = new Users();
                user.setPassword(new BCryptPasswordEncoder().encode(password));
                user.setPhone(phone);
                int re = usersMapper.updateByPhone(user);
                if (re == 1) {
                    //去掉手机验证码
                    redisTemplate.delete(phone);
                    String thing = "用户：{" + phone + "}重置了密码";
                    logsService.addLog(thing);
                }
                return re;
            } else {
                return 2;
            }
        } else {
            return 0;
        }
    }

    @Override
    public int changePhone(Users user, String code, String phone) {
        String s = String.valueOf(redisTemplate.opsForValue().get(phone));
        if (s != null) {
            if (code.equals(s)) {
                user.setPhone(phone);
                int re = usersMapper.updateByPrimaryKeySelective(user);
                if (re == 1) {
                    //去掉手机验证码
                    redisTemplate.delete(phone);
                    Set<String> keys = redisTemplate.keys("*");
                    for (String key : keys) {
                        System.out.println(key);
                        Users oldUser = null;
                        try {
                            oldUser = (Users) redisTemplate.opsForValue().get(key);
                            if (oldUser.getId().equals(user.getId())) {
                                System.out.println("去掉旧token");
                                redisTemplate.delete(key);
                                break;
                            }
                        } catch (Exception e) {
//                            e.printStackTrace();
                            System.out.println("转换失败" + key);
                        }

                    }
                    String thing = "用户：{" + user.getPhone() + "--" + user.getUsername() + "}修改了密码";
                    logsService.addLog(thing);
                }
                return re;
            } else {
                return 2;
            }
        } else {
            return 0;
        }
    }

    @Override
    public Users selectUser(Long id) {
        Users user = usersMapper.selectByPrimaryKey(id);
        return user;
    }

    //查询系部人数
    @Override
    public Long selectCount(Users user) {
        Long count = usersMapper.selectCount(user);
        return count;
    }

    @Override
    public int addManager(Users user, Long id, String dept) {
        Users u = new Users();
        u.setPower("Max");
        u.setDept(dept);
        u.setId(id);
        int re = usersMapper.updateByPrimaryKeySelective(u);
        if (re == 1) {
            String thing = "超级管理员：{" + user.getPhone() + "--" + user.getUsername() + "}添加了部门负责人：" + id;
            logsService.addLog(thing);
        }
        return re;
    }

    //查询部门负责人
    @Override
    public List<Users> selectUserByPower() {
        Users user = new Users();
        user.setPower("Max");
        List<Users> users = usersMapper.selectUser(user);
        return users;
    }

    //删除部门负责人
    @Override
    public int deleteManager(Users user, Long id) {
        Users u = new Users();
        u.setId(id);
        u.setPower("");
        int re = usersMapper.updateByPrimaryKeySelective(u);
        if (re == 1) {
            String thing = "超级管理员：{" + user.getPhone() + "--" + user.getUsername() + "}删除了部门负责人：" + id;
            logsService.addLog(thing);
        }
        return re;
    }

    //查询部门人员
    @Override
    public List<Users> selectUsersByDept(String dept) {
        Users user = new Users();
        user.setDept(dept);
        List<Users> users = usersMapper.selectUser(user);
        return users;
    }

//    //部门负责人删除部门成员
//    @Override
//    public int deleteUserByDept(Users user, Long id) {
//        Users u = new Users();
//        u.setDept(user.getDept());
//        u.setId(id);
//        int re = usersMapper.deleteUserByDept(u);
//        if (re == 1) {
//            String thing = "部门负责人：{" + user.getPhone() + "--" + user.getUsername() + "}删除了部门成员：" + id;
//            logsService.addLog(thing);
//        }
//        return re;
//    }


    @Override
    public List<Users> selectAllUser() {
        List<Users> users = usersMapper.selectAllUser();
        return users;
    }

    @Override
    public int updatePasswordNoAuth(Long id, String password) {
        Users user = new Users();
        user.setId(id);
        //密码加密
        user.setPassword(new BCryptPasswordEncoder().encode(password));
        int re = usersMapper.updateByPrimaryKeySelective(user);
        return re;
    }

    @Override
    public Long logout(String token) {

        Boolean delete = redisTemplate.delete(token);
        if (delete == true) {
            return Long.valueOf(1);
        } else {
            return Long.valueOf(0);
        }
    }

    @Override
    public int deleteDeptUser(Users user, Long id) {
        //部门负责人从用户表中将该用户逻辑删除。
        Users u = usersMapper.selectByPrimaryKey(id);
        Admins a = adminsMapper.selectByPrimaryKey(id);
        Workers w = workersMapper.selectByPrimaryKey(id);
        if (u == null) {
            return 0;   //用户不存在
        } else if (a != null) {
            return 101; //非法删除管理员
        } else if (w != null) {
            return 102; //非法删除维修人员
        } else if ("Max".equals(u.getPower())) {
            return 103; //非法删除部门负责人
        } else if (!user.getDept().equals(u.getDept())) {
            return 104; //非法删除非本部门人员
        } else if (id.equals(user.getId())) {
            return 105; //非法删除本人
        } else {
            u.setId(id);
            u.setDeleted(1);
            int re2 = usersMapper.updateByPrimaryKeySelective(u);
            //如果该账号在线，进行强制下线
            Set<String> keys = redisTemplate.keys("*");
            for (String key : keys) {
                System.out.println(key);
                Users oldUser = null;
                try {
                    oldUser = (Users) redisTemplate.opsForValue().get(key);
                    if (id.equals(oldUser.getId())) {
                        System.out.println("账号已经登录，强制下线");
                        //将别处登录的账号key删除，即踢下线
                        redisTemplate.delete(key);
                        break;
                    }
                } catch (Exception e) {
//                        e.printStackTrace();
                    System.out.println("转换失败" + key);
                }
            }
            if (re2 == 1) {
                String thing = "部门负责人：{" + user.getPhone() + "--" + user.getUsername() + "}删除了用户：" + id;
                logsService.addLog(thing);
            }
            return re2;
        }
    }
}
